package com.example.meijun.pantest;

import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by meijun on 17-4-6.
 */

public class ddd {
    private String baseUrl = "http://192.168.248.220:9080/pansoftdfs/";
    private String downurl = "/v2/files/%s/download ";
    private static final String TAG = "DownLoadManager";


    public void downloadFile(String downurl, final File file , String fildid ) {


        String format = String.format(downurl, fildid);
        String url = baseUrl + format;


        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody formBody = new FormBody.Builder()
                .add("fileid", fildid)
                .build();


        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        //here is Asy  but  callback is not in UIThread
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });

    }



    private void parse(Response response, File file) throws IOException {
        InputStream inputStream = response.body().byteStream();


        FileOutputStream fileOutputStream = new FileOutputStream(file);
        int len = 0;
        byte[] b = new byte[1024];
        int total = 0;
        while (-1 != (len=inputStream.read(b))) {
            fileOutputStream.write(b, 0, len);
            total += len;
            Log.e(TAG, "size : 55971   current: " + total);
        }
        fileOutputStream.flush();
        fileOutputStream.close();
    }
}
